package com.hzy.fivepalace.wx.service;


import com.hzy.fivepalace.common.type.WhetherTypeEnum;
import com.hzy.fivepalace.common.util.ResponseUtil;
import com.hzy.fivepalace.db.dao.DtsFeedbackMapper;
import com.hzy.fivepalace.db.dao.UrlConfigMapper;
import com.hzy.fivepalace.db.domain.DtsFeedback;
import com.hzy.fivepalace.db.domain.UrlConfig;
import com.hzy.fivepalace.db.vo.wx.WxFeedbackVo;
import jodd.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 通用服务
 */
@Service
public class WxCommonService {

    @Resource
    private DtsFeedbackMapper feedbackMapper;

    @Resource
    private UrlConfigMapper urlConfigMapper;

    @Resource
    private Redisson redisson;


    /**
     * 获取url配置
     * @return
     */
    public Object getUrlConfig(){
        UrlConfig urlConfig= urlConfigMapper.selectByPrimaryKey(1);
        return ResponseUtil.ok( urlConfig);
    }

    /**
     * 提交意见反馈
     *
     * @param userId
     * @param feedback
     * @return
     */
    public Object submitFeedback(Integer userId, WxFeedbackVo feedback) {
        RLock lock = redisson.getLock("user_feedback_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (StringUtil.isBlank(feedback.getContent())) {
            lock.unlock();
            return ResponseUtil.fail("反馈内容不能不空");
        }
        DtsFeedback feedbackAdd = new DtsFeedback();
        feedbackAdd.setUserId(userId);
        feedbackAdd.setContent(feedback.getContent());
        feedbackAdd.setPicUrls(feedback.getPicUrls());
        feedbackAdd.setHasPicture((feedback.getPicUrls() != null && feedback.getPicUrls().length > 0));
        feedbackAdd.setFeedType("微信小程序端用户反馈");
        feedbackAdd.setStatus(WhetherTypeEnum.NO.getName());
        feedbackAdd.setAddTime(LocalDateTime.now());
        feedbackAdd.setUpdateTime(LocalDateTime.now());
        feedbackAdd.setDeleted(false);
        feedbackMapper.insertSelective(feedbackAdd);
        lock.unlock();
        return ResponseUtil.ok("反馈成功", null);
    }
}
